/*
 * Graphics.cpp
 *
 *  Created on: 08/01/2012
 *      Author: Mariano
 */

#include "Graphics.h"
using namespace std;

Graphics::Graphics(int w, int h) {
	SDL_Init(SDL_INIT_EVERYTHING);
	IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
	screen = SDL_SetVideoMode(w, h, 32, SDL_SWSURFACE);
	running = true;
}

Graphics::~Graphics() {
}

void Graphics::addSpriteInstance(SpriteInstance * sprite) {
	spriteList.push_back(sprite);
}

void Graphics::onKeyDown(SDL_Event * event) {
	if (event->key.keysym.sym == SDLK_ESCAPE)
		running = false;
}

void Graphics::onKeyUp(SDL_Event * event) {
}

void Graphics::drawSprite(SpriteInstance * sprite) {
	SDL_Rect rect;
	rect.w = sprite->getSprite()->getSpriteW();
	rect.h = sprite->getSprite()->getSpriteH();

	rect.x = sprite->getSprite()->getActualFrame() * rect.w;
	rect.y = 0;

	SDL_Rect dst;
	dst.x = sprite->getX() - cam.getX() / 2.0;
	dst.y = screen->h - (sprite->getY() + rect.h - cam.getY() / 2.0);

	SDL_BlitSurface(sprite->getSprite()->getTexture(), &rect, screen, &dst);
}

Camera * Graphics::getCamera() {
	return &cam;
}

bool Graphics::update(int delay) {
	SDL_FillRect(screen, NULL, backgroundColor);

	cam.update();

	list<SpriteInstance *>::iterator s;
	for (s = spriteList.begin(); s != spriteList.end(); s++)
		drawSprite(*s);

	int result = SDL_Flip(screen);
	SDL_Delay(delay);
	return result != -1 && running;
}

void Graphics::quit() {
	IMG_Quit();
	SDL_Quit();
}

void Graphics::setBackgroundColor(Uint32 color) {
	backgroundColor = color;
}
